package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.vo.PageResult;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.dubbo.api.FriendApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(timeout = 10000000)
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(Long userId, Long friendId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        if (!mongoTemplate.exists(query, Friend.class)) {
            // 不存在数据则新增
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(friend);
        }

        query = new Query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        if (!mongoTemplate.exists(query, Friend.class)) {
            // 不存在数据则新增
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(friend);
        }


    }

    @Override
    public PageResult queryContractList(Long userId, Integer page, Integer pagesize, String keyword) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page - 1) * pagesize);

        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);

        return new PageResult(page, pagesize, (int) count, friendList);
    }
}
